package mgr_chat

import (
	"errors"
	"fmt"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_live"
	"longmen/server/pkg/db/mysql/models/models_main"
	"time"
)

// CheckUserMgr 识别用户身份, 创建聊天
func CheckUserMgr(fromUserId, toUserId int) (isMgr bool, chat *models_main.MgrChat, err error) {
	if fromUserId == toUserId {
		return false, nil, errors.New("不能对自己发消息")
	}
	managerUser, _ := db_live.GetLiveRoomManagersParam(map[string]interface{}{
		"mgrid": map[string]interface{}{
			"in": []int{fromUserId, toUserId},
		},
	}, "", 0, 0)
	if len(managerUser) <= 0 {
		return false, nil, errors.New("普通用户之间不能私聊")
	}

	mgrMp := map[int]*models_live.LiveRoomManager{}
	for k, v := range managerUser {
		mgrMp[v.Mgrid] = managerUser[k]
	}

	mgrId, userId, err := func() (int, int, error) {
		//判断出发送者是房管还是用户
		mgr, ok := mgrMp[fromUserId]
		if ok {
			return mgr.Mgrid, toUserId, nil
		}
		mgr, ok = mgrMp[toUserId]
		if ok {
			return mgr.Mgrid, fromUserId, nil
		}
		return 0, 0, errors.New("异常情况")
	}()
	if err != nil {
		return false, nil, err
	}

	chat, err = db_main.GetMgrChat(map[string]interface{}{
		"mgr_id":  mgrId,
		"user_id": userId,
	})
	if err != nil {
		return false, nil, err
	}

	if chat.Id <= 0 {
		chat = &models_main.MgrChat{
			CreatedAt: time.Now(),
			MgrId:     mgrId,
			UserId:    userId,
		}
		err = db_main.InsertMgrChat(chat)
		if err != nil {
			return false, nil, err
		}
	}
	return fromUserId == mgrId, chat, nil
}

// GetChatId 生成私聊历史id
func GetChatId(mgrChat *models_main.MgrChat) string {
	return fmt.Sprintf("%d_%d", mgrChat.MgrId, mgrChat.UserId)
}
